/**
 * Module dependencies.
 */

var express = require('express');
var fs = require('fs');

module.exports = function(parent, options) {
	var verbose = options.verbose;
	fs.readdirSync(__dirname + '/../controllers').forEach(
			function(name) {
				verbose && console.log('\ncontroller %s:', name);
				var obj = require('./../controllers/' + name);
				var name = obj.name || name;
				var prefix = obj.prefix || '';
				var app = express();
				var handler;
				var method;
				var path;

				// allow specifying the view engine
				if (obj.engine)
					app.set('view engine', obj.engine);
				app.set('views', __dirname + '/../controllers/' + name + '/views');

				// generate routes based
				// on the exported methods
				for ( var key in obj) {
					// "reserved" exports
					if (~[ 'name', 'prefix', 'engine', 'beforeAction' ].indexOf(key))
						continue;
					// route exports
					method = 'get';
					if (key.indexOf('_') < 1) {
						// 不存在下划线
						if (name == options.defaultController
								&& key == options.defaultAction) {
							path = '/';
						} else {
							path = '/' + name + '/' + key + '(/*)?';
						}
					} else {
						var _action = key.split('_');
						method = _action[0];
						path = '/' + name + '/' + _action[1] + '(/*)?';
					}
					// setup
					handler = obj[key];
					path = prefix + path;

					// before middleware support
					if (obj.beforeAction) {
						app[method](path, obj.beforeAction, handler);
						verbose && console.log('%s %s -> before -> %s', method.toUpperCase(), path, key);
					} else {
						app[method](path, handler);
						verbose && console.log('%s %s -> %s', method.toUpperCase(), path, key);
					}
				}
				// mount the app
				parent.use(app);
			});
};
